package com.streamkar.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.streamkar.common.es.ExecuteDslComponent;
import com.streamkar.constant.Constants;
import com.streamkar.entity.domain.Talent;
import com.streamkar.service.TalentService;
import com.streamkar.util.EsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TalentServiceImpl
 * @Description
 * @Author tyfrost
 * @Date 2018/11/14 上午12:12
 * @Version 1.0
 */
@Service
public class TalentServiceImpl implements TalentService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TalentServiceImpl.class);

    @Autowired
    ExecuteDslComponent executeDslComponent;

    @Autowired
    EsUtil esUtil;

    @Override
    public JSONArray talentList(Talent talent, int startLevel, int endLevel, String queryValue) {
        String dsl = "{\"_source\":[\"userId\",\"agencyId\",\"nickname\",\"avatar\",\"poster\",\"talentLevel\",\"broadcastTime\",\"totalDiamonds\",\"lastBroadcastTime\",\"lastLoginTime\",\"registerTime\",\"joinTime\",\"newTime\",\"country\",\"location\",\"left\",\"leftReason\",\"updateTime\"],\"query\":{\"bool\":{\"must\":[{\"range\":{\"talentLevel\":{\"gte\":\"{{startLevel}}\",\"lte\":\"{{endLevel}}\"}}},{\"range\":{\"joinTime\":{\"gte\":\"{{startTime}}\",\"lte\":\"{{endTime}}\",\"time_zone\":\"+08:00\"}}}]}},\"from\":\"{{offset}}\",\"size\":\"{{limit}}\",\"sort\":[{\"{{orderBy}}\":{\"order\":\"{{orderByType}}\"}}]}";
        Map<String, String> paramMap = new HashMap<>();
        Map<String, Object> queryValueMap = new HashMap<>();

        // 当must节点和should节点都存在时需要制定should查询范围
        boolean shouldFlag = false;
        if (null != talent.getLeft()) {
            queryValueMap.put("left", talent.getLeft());
        }

        if (null != talent.getAgencyId()) {
            queryValueMap.put("agencyId", talent.getAgencyId());
        }

        if (!CollectionUtils.isEmpty(queryValueMap)) {
            dsl = esUtil.bulidMustDsl(dsl, queryValueMap);
        }

        if (StringUtils.isNotBlank(queryValue)) {
            queryValueMap = new HashMap<>();
            try {
                Long userId = Long.valueOf(queryValue);
                queryValueMap.put("userId", userId);
            } catch (Exception e) {
                LOGGER.info("queryValue can not parse to Long,userId set empty");
            }
            queryValueMap.put("nickname", queryValue);
            dsl = esUtil.bulidShouldDsl(dsl, queryValueMap);
            shouldFlag = true;
        }

        if (shouldFlag) {
            dsl = esUtil.bulidDsl(dsl);
        }

        paramMap.put("startLevel", String.valueOf(startLevel));
        paramMap.put("endLevel", String.valueOf(endLevel));
        paramMap.put("startTime", talent.getStartTime());
        paramMap.put("endTime", talent.getEndTime());
        paramMap.put("offset", String.valueOf(talent.getOffset()));
        paramMap.put("limit", String.valueOf(talent.getLimit()));
        paramMap.put("orderBy", talent.getOrderBy());
        paramMap.put("orderByType", talent.getOrderByType());
        JSONArray jsonArray = executeDslComponent.executeDsl(Constants.INDEX_TALENT, dsl, paramMap);
        return jsonArray;
    }

    @Override
    public Talent talentInfo(Integer userId) {
        Talent talent = null;
        if (null == userId) {
            LOGGER.error("userId is null,return null");
            return talent;
        }
        String dsl = "{\"_source\":[\"userId\",\"agencyId\",\"nickname\",\"avatar\",\"poster\",\"talentLevel\",\"broadcastTime\",\"totalDiamonds\",\"lastBroadcastTime\",\"lastLoginTime\",\"registerTime\",\"joinTime\",\"newTime\",\"country\",\"location\",\"isLeft\",\"leftReason\",\"updateTime\"],\"query\":{\"bool\":{\"must\":[{\"term\":{\"userId\":{{userId}}}}]}}}";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", String.valueOf(userId));
        JSONArray jsonArray = executeDslComponent.executeDsl(Constants.INDEX_TALENT, dsl, paramMap);
        if (!CollectionUtils.isEmpty(jsonArray)) {
            talent = jsonArray.getObject(0, Talent.class);
        }
        return talent;
    }

    @Override
    public JSONArray talentUserStat(Integer userId) {
        if (null == userId) {
            LOGGER.error("userId is null,return null");
            return new JSONArray();
        }
        String dsl = "{\"_source\":[\"id\",\"userId\",\"agencyId\",\"country\",\"date\",\"talentLevel\",\"joinTime\",\"broadcastTime\",\"totalDiamonds\",\"updateTime\"],\"query\":{\"bool\":{\"must\":[{\"term\":{\"userId\":{{userId}}}},{\"range\":{\"date\":{\"lte\":\"{{endTime}}\",\"gte\":\"{{startTime}}\",\"time_zone\":\"+08:00\"}}}]}},\"sort\":[{\"date\":{\"order\":\"asc\"}}]}";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", String.valueOf(userId));
        // 当前月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        paramMap.put("endTime", sdf.format(calendar.getTime()));
        // 统计前几个月的数据
        calendar.add(Calendar.MONTH, Constants.STAT_MONTH);
        paramMap.put("startTime", sdf.format(calendar.getTime()));
        JSONArray jsonArray = executeDslComponent.executeDsl(Constants.INDEX_TALENT_STAT, dsl, paramMap);
        return jsonArray;
    }
}
